from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask_login import login_user, login_required, logout_user, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from app.models import User, News, BilingualContent, Contact
from app import db  # 直接从app导入db实例

admin = Blueprint('admin', __name__)

@admin.route('/login', methods=['GET', 'POST'])
def login():
    # 如果用户已登录，重定向到管理面板
    if current_user.is_authenticated:
        return redirect(url_for('admin.dashboard'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        user = User.query.filter_by(username=username).first()
        
        if user and check_password_hash(user.password, password):
            login_user(user)
            flash('登錄成功！', 'success')
            # 获取next参数，如果没有则默认跳转到dashboard
            next_page = request.args.get('next')
            return redirect(next_page or url_for('admin.dashboard'))
        else:
            flash('用戶名或密碼錯誤！', 'danger')
    
    return render_template('admin/login.html')

@admin.route('/logout')
@login_required
def logout():
    logout_user()
    flash('您已成功登出！', 'info')
    return redirect(url_for('admin.login'))

@admin.route('/dashboard')
@login_required
def dashboard():
    # 获取统计数据
    news_count = News.query.count()
    cases_count = BilingualContent.query.filter_by(category='case').count()
    contacts_count = Contact.query.filter_by(status='pending').count()
    visits_count = 0  # 这里可以接入访问统计系统
    
    # 获取最新咨询
    latest_contacts = Contact.query.order_by(Contact.created_at.desc()).limit(5).all()
    
    # 获取最新文章
    latest_news = News.query.order_by(News.publish_date.desc()).limit(5).all()
    
    return render_template('admin/dashboard.html',
                         news_count=news_count,
                         cases_count=cases_count,
                         contacts_count=contacts_count,
                         visits_count=visits_count,
                         latest_contacts=latest_contacts,
                         latest_news=latest_news)

@admin.route('/content/manage')
@login_required
def manage_content():
    # 内容管理逻辑
    return render_template('admin/content_manage.html')

@admin.route('/db')
@login_required
def database_console():
    return render_template('admin/db_console.html')

@admin.route('/contacts')
@login_required
def contacts():
    # 获取所有咨询，按时间倒序排列
    page = request.args.get('page', 1, type=int)
    status = request.args.get('status', 'all')
    
    query = Contact.query
    
    # 根据状态筛选
    if status != 'all':
        query = query.filter_by(status=status)
    
    # 分页，每页15条
    contacts = query.order_by(Contact.created_at.desc())\
                   .paginate(page=page, per_page=15, error_out=False)
    
    return render_template('admin/contacts.html', 
                         contacts=contacts,
                         current_status=status)

@admin.route('/contacts/<int:contact_id>/status', methods=['POST'])
@login_required
def update_contact_status(contact_id):
    contact = Contact.query.get_or_404(contact_id)
    new_status = request.form.get('status')
    
    if new_status in ['pending', 'processed']:
        contact.status = new_status
        db.session.commit()
        flash('狀態更新成功！', 'success')
    else:
        flash('無效的狀態！', 'danger')
    
    return redirect(url_for('admin.contacts'))

@admin.route('/contacts/<int:contact_id>/delete', methods=['POST'])
@login_required
def delete_contact(contact_id):
    contact = Contact.query.get_or_404(contact_id)
    db.session.delete(contact)
    db.session.commit()
    flash('諮詢已刪除！', 'success')
    return redirect(url_for('admin.contacts'))

@admin.route('/news')
@login_required
def news():
    page = request.args.get('page', 1, type=int)
    news_list = News.query.order_by(News.publish_date.desc())\
                    .paginate(page=page, per_page=10, error_out=False)
    return render_template('admin/news.html', news=news_list)

@admin.route('/news/add', methods=['GET', 'POST'])
@login_required
def add_news():
    if request.method == 'POST':
        news = News(
            zh_title=request.form.get('zh_title'),
            en_title=request.form.get('en_title'),
            zh_content=request.form.get('zh_content'),
            en_content=request.form.get('en_content'),
            category=request.form.get('category')
        )
        db.session.add(news)
        db.session.commit()
        flash('資訊添加成功！', 'success')
        return redirect(url_for('admin.news'))
    return render_template('admin/news_form.html')

@admin.route('/news/<int:news_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_news(news_id):
    news = News.query.get_or_404(news_id)
    if request.method == 'POST':
        news.zh_title = request.form.get('zh_title')
        news.en_title = request.form.get('en_title')
        news.zh_content = request.form.get('zh_content')
        news.en_content = request.form.get('en_content')
        news.category = request.form.get('category')
        db.session.commit()
        flash('資訊更新成功！', 'success')
        return redirect(url_for('admin.news'))
    return render_template('admin/news_form.html', news=news)

@admin.route('/news/<int:news_id>/delete', methods=['POST'])
@login_required
def delete_news(news_id):
    news = News.query.get_or_404(news_id)
    db.session.delete(news)
    db.session.commit()
    flash('資訊已刪除！', 'success')
    return redirect(url_for('admin.news'))

@admin.route('/services')
@login_required
def services():
    page = request.args.get('page', 1, type=int)
    services = BilingualContent.query.filter_by(category='service')\
                                   .order_by(BilingualContent.created_at.desc())\
                                   .paginate(page=page, per_page=10, error_out=False)
    return render_template('admin/services.html', services=services)

@admin.route('/services/add', methods=['GET', 'POST'])
@login_required
def add_service():
    if request.method == 'POST':
        service = BilingualContent(
            zh_title=request.form.get('zh_title'),
            en_title=request.form.get('en_title'),
            zh_content=request.form.get('zh_content'),
            en_content=request.form.get('en_content'),
            category='service',
            images=request.form.get('images', '')
        )
        db.session.add(service)
        db.session.commit()
        flash('業務範圍添加成功！', 'success')
        return redirect(url_for('admin.services'))
    return render_template('admin/service_form.html')

@admin.route('/services/<int:service_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_service(service_id):
    service = BilingualContent.query.get_or_404(service_id)
    if request.method == 'POST':
        service.zh_title = request.form.get('zh_title')
        service.en_title = request.form.get('en_title')
        service.zh_content = request.form.get('zh_content')
        service.en_content = request.form.get('en_content')
        service.images = request.form.get('images', '')
        db.session.commit()
        flash('業務範圍更新成功！', 'success')
        return redirect(url_for('admin.services'))
    return render_template('admin/service_form.html', service=service)

@admin.route('/services/<int:service_id>/delete', methods=['POST'])
@login_required
def delete_service(service_id):
    service = BilingualContent.query.get_or_404(service_id)
    db.session.delete(service)
    db.session.commit()
    flash('業務範圍已刪除！', 'success')
    return redirect(url_for('admin.services'))

@admin.route('/cases')
@login_required
def cases():
    page = request.args.get('page', 1, type=int)
    cases = BilingualContent.query.filter_by(category='case')\
                                 .order_by(BilingualContent.created_at.desc())\
                                 .paginate(page=page, per_page=10, error_out=False)
    return render_template('admin/cases.html', cases=cases)

@admin.route('/cases/add', methods=['GET', 'POST'])
@login_required
def add_case():
    if request.method == 'POST':
        case = BilingualContent(
            zh_title=request.form.get('zh_title'),
            en_title=request.form.get('en_title'),
            zh_content=request.form.get('zh_content'),
            en_content=request.form.get('en_content'),
            category='case',
            images=request.form.get('images', '')
        )
        db.session.add(case)
        db.session.commit()
        flash('成功案例添加成功！', 'success')
        return redirect(url_for('admin.cases'))
    return render_template('admin/case_form.html')

@admin.route('/cases/<int:case_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_case(case_id):
    case = BilingualContent.query.get_or_404(case_id)
    if request.method == 'POST':
        case.zh_title = request.form.get('zh_title')
        case.en_title = request.form.get('en_title')
        case.zh_content = request.form.get('zh_content')
        case.en_content = request.form.get('en_content')
        case.images = request.form.get('images', '')
        db.session.commit()
        flash('成功案例更新成功！', 'success')
        return redirect(url_for('admin.cases'))
    return render_template('admin/case_form.html', case=case)

@admin.route('/cases/<int:case_id>/delete', methods=['POST'])
@login_required
def delete_case(case_id):
    case = BilingualContent.query.get_or_404(case_id)
    db.session.delete(case)
    db.session.commit()
    flash('成功案例已刪除！', 'success')
    return redirect(url_for('admin.cases'))

@admin.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    if request.method == 'POST':
        # 处理密码修改
        if 'change_password' in request.form:
            old_password = request.form.get('old_password')
            new_password = request.form.get('new_password')
            confirm_password = request.form.get('confirm_password')
            
            if not check_password_hash(current_user.password, old_password):
                flash('原密碼不正確！', 'danger')
            elif new_password != confirm_password:
                flash('兩次輸入的新密碼不一致！', 'danger')
            else:
                current_user.password = generate_password_hash(new_password)
                db.session.commit()
                flash('密碼修改成功！', 'success')
                return redirect(url_for('admin.logout'))
        
        # 处理网站设置
        elif 'update_settings' in request.form:
            # 这里可以添加其他网站设置的保存逻辑
            flash('設置保存成功！', 'success')
            
    return render_template('admin/settings.html') 